package com.hangyutech.strelitzia.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * @Author: 阿里云OSS涉及资源
 * @Date: 2019/12/11 4:08 下午
 */

@Component
public class OssClientFactory implements FactoryBean<OSS>, InitializingBean, DisposableBean {

    private OSS ossClient;

    @Autowired
    private AliYunConfig ossConfig;

    public OssClientFactory(AliYunConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    @Override
    public OSS getObject() {
        return this.ossClient;
    }

    @Override
    public Class<?> getObjectType() {
        return OSSClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() {
        if (Objects.nonNull(this.ossClient)) {
            this.ossClient.shutdown();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.ossClient = new OSSClientBuilder().build(
                "https://" + ossConfig.getEndpoint() + ".aliyuncs.com",
                ossConfig.getOssAccessKeyId(),
                ossConfig.getOssAccessKeySecret()
        );
    }

}